#!/usr/bin/env bash
# Usage: compare_planner_main.sh <input_trace> <planner_out>
# Run planner and main.py in parallel on the same input. If main.py finishes (no TIMEOUT)
# and its reported Fin time is strictly smaller than planner's Fin, overwrite planner_out with main's output.

set -eu

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <input_trace> <planner_out>"
  exit 2
fi

INPUT="$1"
PLANNER_OUT="$2"


PLANNER_BIN=$"./planner" || {
  echo "planner binary not found in PATH or common locations" >&2
  exit 3
}

# Temporary files
PLANNER_TMP="${PLANNER_OUT}.planner_tmp"
SMT_TMP="${PLANNER_OUT}.smt_tmp"

MAIN_FORMAL_OUT="${PLANNER_OUT}"  
MAIN_ALT_OUT="${INPUT}.out"                       # fallback: some mains write input.out

# remove old tmp files if any
rm -f "$PLANNER_TMP" "$MAIN_FORMAL_OUT" "$MAIN_ALT_OUT"


# Run planner and main.py in parallel
echo "Starting planner ($PLANNER_BIN) and main.py on input $INPUT..."
("$PLANNER_BIN" < "$INPUT" > "$PLANNER_TMP") &
PID_PLANNER=$!

# Start main.py (assumes Python 3 and main.py available at /home/heziy/heterogeneous_systems_programming/2025/solver/main.py)
# main.py supports taking input file path or content as first arg in our environment
python3 /home/heziy/heterogeneous_systems_programming/2025/solver/main.py  "$INPUT" "$SMT_TMP" &
PID_MAIN=$!

# wait for both with a timeout of 10 seconds
( sleep 10 && kill $PID_PLANNER $PID_MAIN 2>/dev/null & ) &
wait $PID_PLANNER || echo "planner exited with non-zero status"
wait $PID_MAIN || echo "main.py exited with non-zero status or timed out"

PLANNER_SUMMARY="./tests/planner_summary.txt"
SMT_SUMMARY="./tests/smt_summary.txt"
CHECKER_BIN="./../checker/checker"
# Redirect both stdout and stderr from checker into the summary files. Some checker messages
# (warnings/errors) are printed to stderr, so a plain >file only captured stdout.
"$CHECKER_BIN" "$INPUT" "$PLANNER_TMP" "$PLANNER_TMP" > "$PLANNER_SUMMARY" 2>&1 || echo "checker failed for planner output" >&2
"$CHECKER_BIN" "$INPUT" "$SMT_TMP" "$SMT_TMP" > "$SMT_SUMMARY" 2>&1 || echo "checker failed for smt output" >&2



# Read Fin values from checker summaries (format: "ok All tasks finish at 7000").
# Only accept the number if the line starts with "ok".
SMT_LAST_FIN="none"
PLANNER_LAST_FIN="none"
if [ -f "$SMT_SUMMARY" ]; then
  # find the last matching line that starts with 'ok All tasks finish at <num>'
  matched_line=$(grep -E '^ok[[:space:]]+All[[:space:]]+tasks[[:space:]]+finish[[:space:]]+at[[:space:]]+[0-9]+' "$SMT_SUMMARY" | tail -n 1 || true)
  if [[ "$matched_line" =~ ^ok[[:space:]]+All[[:space:]]+tasks[[:space:]]+finish[[:space:]]+at[[:space:]]+([0-9]+)$ ]]; then
    SMT_LAST_FIN="${BASH_REMATCH[1]}"
  else
    SMT_LAST_FIN="none"
  fi
fi

if [ -f "$PLANNER_SUMMARY" ]; then
  matched_line=$(grep -E '^ok[[:space:]]+All[[:space:]]+tasks[[:space:]]+finish[[:space:]]+at[[:space:]]+[0-9]+' "$PLANNER_SUMMARY" | tail -n 1 || true)
  if [[ "$matched_line" =~ ^ok[[:space:]]+All[[:space:]]+tasks[[:space:]]+finish[[:space:]]+at[[:space:]]+([0-9]+)$ ]]; then
    PLANNER_LAST_FIN="${BASH_REMATCH[1]}"
  else
    PLANNER_LAST_FIN="none"
  fi
fi

echo "SMT last Fin: ${SMT_LAST_FIN:-<none>}"
echo "Planner last Fin: ${PLANNER_LAST_FIN:-<none>}"

## Decide which temp file is better (smaller Fin). Set MAIN_FORMAL_OUT to the better one.
MAIN_FORMAL_OUT=""
if [[ "$SMT_LAST_FIN" == "none" && "$PLANNER_LAST_FIN" == "none" ]]; then
  echo "Neither solver produced a numeric Fin; no output will be copied."
elif [[ "$SMT_LAST_FIN" != "none" && "$PLANNER_LAST_FIN" == "none" ]]; then
  MAIN_FORMAL_OUT="$SMT_TMP"
elif [[ "$SMT_LAST_FIN" == "none" && "$PLANNER_LAST_FIN" != "none" ]]; then
  MAIN_FORMAL_OUT="$PLANNER_TMP"
else
  # both numeric -> choose smaller
  if [ "$SMT_LAST_FIN" -lt "$PLANNER_LAST_FIN" ]; then
    MAIN_FORMAL_OUT="$SMT_TMP"
  else
    MAIN_FORMAL_OUT="$PLANNER_TMP"
  fi
fi

if [ -n "$MAIN_FORMAL_OUT" ] && [ -f "$MAIN_FORMAL_OUT" ]; then
  echo "Chosen best output: $MAIN_FORMAL_OUT -> will copy to $PLANNER_OUT"
  cp "$MAIN_FORMAL_OUT" "$PLANNER_OUT"
else
  echo "No valid output produced by either solver; leaving $PLANNER_OUT untouched if it exists"
fi

# delete temporary files
# rm -f "$PLANNER_TMP" "$SMT_TMP" "$PLANNER_SUMMARY" "$SMT_SUMMARY"

exit 0